#!/bin/bash

PROC_DIR="/host/proc"

os_distro_talos="talos"
os_distro=""

get_os_distro() {
  local version_info=$(< $PROC_DIR/version)

  [[ $version_info =~ $os_distro_talos ]] && os_distro=$os_distro_talos
}

target_pid=1

get_pid() {
  local process_name=$1
  local pid
  local status_file
  local name

  for dir in $PROC_DIR/*/; do
    pid=$(basename "$dir")
    status_file="$PROC_DIR/$pid/status"

    if [ -f "$status_file" ]; then
      while IFS= read -r line; do
        if [[ $line == "Name:"* ]]; then
          name="${line#*:}"
          name="${name//[$'\t ']/}"  # Remove both spaces and tabs
          break  # Exit the loop once the Name is found
        fi
      done < "$status_file"
    fi

    if [ "$name" = "$process_name" ]; then
      target_pid=$pid
    fi
  done
}

get_os_distro

[[ $os_distro = $os_distro_talos ]] && get_pid "kubelet"

# Use namespace files instead of -t to avoid the need for HostPID.
ns_dir="$PROC_DIR/$target_pid/ns"
ns_mnt="$ns_dir/mnt"
ns_net="$ns_dir/net"
ns_uts="$ns_dir/uts"

nsenter --mount="$ns_mnt" --net="$ns_net" --uts="$ns_uts" -- "$@"
